package com.xcdh.commons.ds;

import com.xcdh.commons.annotation.DataSourceSwitch;
import com.xcdh.commons.consts.DataSourceType;
import com.xcdh.commons.utils.DataSourceContextHolder;
import com.xcdh.commons.utils.IFUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class DataSourceSwitchConfiguration {

    @Pointcut("@annotation(com.xcdh.commons.annotation.DataSourceSwitch) || within(@com.xcdh.commons.annotation.DataSourceSwitch *) ")
    public void dataSourcePointCut() {}

    // 切入点执行前拦截
    @Before("dataSourcePointCut() && @annotation(dataSourceSwitch)")
    public void switchDataSourceByAnnotation(JoinPoint joinPoint, DataSourceSwitch dataSourceSwitch) {
        String dataSourceName = dataSourceSwitch.value();
        DataSourceContextHolder.set(IFUtils.nvlString(dataSourceName , DataSourceType.MASTER));
    }

    // 切入点执行后恢复
    @After("dataSourcePointCut()")
    public void restoreDataSource(JoinPoint joinPoint) {
        DataSourceContextHolder.clear();
    }
}

